package com.liujie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liujie.common.R;
import com.liujie.dto.DishDto;
import com.liujie.entity.Category;
import com.liujie.entity.Dish;
import com.liujie.entity.DishFlavor;
import com.liujie.service.CategoryService;
import com.liujie.service.DishFlavorService;
import com.liujie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        boolean b = dishService.saveWithFlavor(dishDto);
        if (b) {
            //清理缓存数据
            Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
            return R.success("添加菜品成功");
        }
        return R.error("添加菜品失败");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getSort);
        dishService.page(pageInfo, lqw);

        //拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            dishDto.setCategoryName(categoryService.getById(record.getCategoryId()).getName());
            dishDtos.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> getOne(@PathVariable long id) {
        DishDto dishDto = dishService.getOneWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        boolean b = dishService.updateWithFlavor(dishDto);
        if (b) {
            //清理缓存数据
            Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
            return R.success("修改菜品信息成功");
        }
        return R.error("修改菜品信息失败");
    }

    @PostMapping("/status/0")
    public R<String> updateStatus0(long[] ids) {
        boolean b = false;
        for (long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(0);
            b = dishService.updateById(dish);
        }

        if (b) {
            //清理缓存数据
            Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
            return R.success("菜品停售成功");
        }
        return R.error("菜品停售失败");
    }

    @PostMapping("/status/1")
    public R<String> updateStatus1(long[] ids) {
        boolean b = false;
        for (long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(1);
            b = dishService.updateById(dish);
        }
        if (b) {
            //清理缓存数据
            Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
            return R.success("菜品启售成功");
        }
        return R.error("菜品启售失败");
    }

    @DeleteMapping
    public R<String> delete(long[] ids) {
        boolean b = false;
        for (long id : ids) {
            b = dishService.deleteWithFlavor(id);
        }
        if (b) {
            //清理缓存数据
            Set keys = redisTemplate.keys("dish_*");
            redisTemplate.delete(keys);
            return R.success("删除菜品成功");
        }
        return R.error("删除菜品失败");
    }

    //    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        List<Dish> dishes = dishService.list(new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, dish.getCategoryId())
//                .eq(Dish::getStatus,1)
//                .orderByAsc(Dish::getSort)
//                .orderByDesc(Dish::getUpdateTime));
//        if (dishes.size()>0){
//            return R.success(dishes);
//        }
//        return R.error("部分菜系无售卖的菜品");
//    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从Redis获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            //存在，无需查询数据库
            return R.success(dishDtos);
        }

        dishDtos=new ArrayList<>();
        List<Dish> dishes = dishService.list(new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1)
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime));

        for (Dish d : dishes) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(d, dishDto);
            dishDto.setCategoryName(categoryService.getById(d.getCategoryId()).getName());
            dishDto.setFlavors(dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, d.getId())));
            dishDtos.add(dishDto);
        }

        if (dishDtos.size() > 0) {
            //不存在，加入缓存
            redisTemplate.opsForValue().set(key, dishDtos, 5, TimeUnit.MINUTES);
            return R.success(dishDtos);
        }
        return R.error("部分菜系无售卖的菜品");
    }
}
